<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\model\ProjectWeeksWorkcontent;
use app\api\model\ProjectWeeksWorkcontent as ProjectWeeksWorkcontentModel;
use app\api\model\ProjectWeeksWorkplan;
use app\api\model\ProjectWeeksWorkplan as ProjectWeeksWorkplanModel;
use app\Request;
use app\api\model\ProjectWeeks as ProjectWeeksModel;
use think\facade\Db;

class Week extends Base
{
    public function weeklist(Request $request)
    {
        try {

            $CurrMonth = strtotime(date('Y-m'));
            $page = $request->param('page');
            $pagesize = $request->param('pagesize');
            $uid = $request->param('uid');
            $ProjectWeeksModel = new ProjectWeeksModel();
            $list = $ProjectWeeksModel->alias('w')
                    ->field('w.week,w.id,w.uid,w.project_id,w.class_id,w.stage_id,w.main_content,w.project_desc,
                    pro.project_no,pro.project_name,u.realname as project_pm,m.main_content as curr_moth_plan,
                    (SELECT GROUP_CONCAT(content) FROM (select concat(content,"（",percentage,"%）\n ") as content,weeks_id FROM zt_project_weeks_workcontent ) t where weeks_id = w.id) as content,
                    (SELECT GROUP_CONCAT(next_content) FROM (select concat(next_content,"（",next_percentage,"%）\n ") as next_content,weeks_id FROM zt_project_weeks_workplan ) tt where weeks_id = w.id) as next_content'
                    )
                    ->join('project_info pro','w.project_id = pro.id')
                    ->leftjoin('user u','pro.project_pm = u.id')
                    ->leftjoin('project_months m','pro.id = m.project_id  and month ='.$CurrMonth)
                    ->where('u.id','=',$uid)
                    ->order('w.week desc,w.id desc')
                    ->paginate([
                        'list_rows'=> $pagesize,
                        'var_page' => 'page',
                        'page'=>$page
                    ]);
            //return $ProjectWeeksModel->getLastSql();
            $result = ["status"=>true,"msg"=>"获取成功！","data"=>$list];
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }

    }

    public function preweekdeail(Request $request){
        try {
            $uid = $request->param('uid');
            $preweek = date('W')-1;
            //return $preweek;
            $project_id = $request->param('project_id');
            $CurrMonth = date("Y-m", strtotime("-1 month")) ;
            if($uid && $project_id){
                $ProjectWeeks = new ProjectWeeksModel();
                $detail = $ProjectWeeks->alias('w')
                    ->field('w.id,w.uid,w.project_id,w.class_id,p.name as class_name,w.stage_id,w.project_desc,w.main_content,i.project_no,m.main_content as curr_moth_plan')
                    ->leftjoin('project_class p','w.class_id = p.id')
                    ->leftjoin('project_info i','w.project_id = i.id')
                    ->leftjoin('project_months m','i.id = m.project_id and i.uid = m.uid and month ='.$CurrMonth)
                    ->where('w.uid','=',$uid)
                    ->where('w.week','=',$preweek)
                    ->where('w.project_id','=',$project_id)
                    ->find();
                if($detail){
                    $id = $detail['id'];
                    $ProjectWeeksWorkplan = new ProjectWeeksWorkplanModel;
                    $workplan = $ProjectWeeksWorkplan->field('next_content,next_percentage')->where('weeks_id',$id)->select();
                    $detail['workplan'] = $workplan;

                    unset($detail['update_time']);
                    unset($detail['create_time']);
                    $result =  ["status"=>true,"msg"=>"获取成功！","data"=>$detail];
                }else{
                    $result =  ["status"=>false,"msg"=>"获取失败！","data"=>$detail];
                }
                return json($result);
            }else{
                $result = ["status"=>false,"msg"=>"参数必须"];
                return json($result);
            }

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function weekadd(Request $request)
    {
        try {

            Db::startTrans();
            $data = [];
            if($request->param('project_id')) $data['project_id'] = $request->param('project_id');
            if($request->param('class_id')) $data['class_id'] = $request->param('class_id');
            if($request->param('stage_id')) $data['stage_id'] = $request->param('stage_id');
            if($request->param('main_content')) $data['main_content'] = $request->param('main_content');
            if($request->param('uid')) $data['uid'] = $request->param('uid');
            if($request->param('project_desc')) $data['project_desc'] = $request->param('project_desc');
            $data['create_time'] = time();
            $data['week'] =  date('W');

            $ProjectWeeksModel = new ProjectWeeksModel;
            $weekinfo = $ProjectWeeksModel->where('week','=',$data['week'])
                                          ->where('uid','=',$data['uid'])
                                          ->where('project_id','=',$data['project_id'])
                                          ->find();
            if($weekinfo){
                $result = ["status"=>false,"re_id"=>"","msg"=>"周报已提交过，请不要重复提交当周周报！"];
                return json($result);
            }

            $re = $ProjectWeeksModel->insertGetId($data);

            $workconent = $request->param('workcontent');
            $workcontent_data = [];
            if(isset($workconent)){
                foreach ($workconent as $v){
                    $v['uid'] =  $data['uid'];
                    $v['weeks_id'] = $re;
                    $v['create_time'] = time();
                    $workcontent_data[] = $v;
                }
                $ProjectWeeksWorkcontent = new ProjectWeeksWorkcontentModel();
                $re_one = $ProjectWeeksWorkcontent->insertAll($workcontent_data);
            }
            $workplan = $request->param('workplan');
            $workplan_data = [];
            if(isset($workplan)){
                foreach ($workplan as $vv){
                    $vv['uid'] =  $data['uid'];
                    $vv['weeks_id'] = $re;
                    $vv['create_time'] = time();
                    $workplan_data[] = $vv;
                }
                $ProjectWorkplan = new ProjectWeeksWorkplanModel();
                $re_two = $ProjectWorkplan->insertAll($workplan_data);
            }

            if($re && $re_one && $re_two){
                Db::commit();
                $result = ["status"=>true,"re_id"=>$re,"msg"=>"添加成功！"];
            }else{
                Db::rollback();
                $result = ["status"=>false,"re_id"=>"","msg"=>"添加失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            Db::rollback();
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function weekdetail(Request $request){
        try {
            $id = $request->param('id');
            $CurrMonth = strtotime(date('Y-m'));
            if($id){
                $ProjectWeeks = new ProjectWeeksModel();
                $detail = $ProjectWeeks->alias('w')
                                       ->field('w.id,w.uid,w.project_id,w.class_id,w.project_desc,p.name as class_name,w.stage_id,w.main_content,i.project_no,m.main_content as curr_moth_plan')
                                       ->leftjoin('project_class p','w.class_id = p.id')
                                       ->leftjoin('project_info i','w.project_id = i.id')
                                       ->leftjoin('project_months m','i.id = m.project_id and i.project_skiller = m.uid and month ='.$CurrMonth)
                                       ->where('w.id',$id)->find();

                $ProjectWeeksWorkcontent = new ProjectWeeksWorkcontentModel;
                $workcontent = $ProjectWeeksWorkcontent->field('content,percentage')->where("weeks_id",$id)->select(); 
                $detail['workcontent'] = $workcontent;

                $ProjectWeeksWorkplan = new ProjectWeeksWorkplanModel;
                $workplan = $ProjectWeeksWorkplan->field('next_content,next_percentage')->where('weeks_id',$id)->select();
                $detail['workplan'] = $workplan;

                unset($detail['update_time']);
                unset($detail['create_time']);
                $result =  ["status"=>true,"msg"=>"获取成功！","data"=>$detail];
                return json($result);
            }else{
                $result = ["status"=>false,"msg"=>"参数必须"];
                return json($result);
            }

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function weeksave(Request $request)
    {
        try {

            Db::startTrans();
            $data = [];
            $id = $request->param('id');
            if($request->param('project_id')) $data['project_id'] = $request->param('project_id');
            if($request->param('class_id')) $data['class_id'] = $request->param('class_id');
            if($request->param('stage_id')) $data['stage_id'] = $request->param('stage_id');
            if($request->param('uid')) $data['uid'] = $request->param('uid');
            $data['main_content'] = $request->param('main_content');
            $data['project_desc'] = $request->param('project_desc');
            $data['update_time'] = time();

            $ProjectWeeksModel = new ProjectWeeksModel;
            $re = $ProjectWeeksModel->where('id',$id)->save($data);

            //先删除后增加
            $ProjectWeeksWorkcontent = new ProjectWeeksWorkcontentModel();
            $ProjectWeeksWorkcontent->where('weeks_id',$id)->delete();

            $workconent = $request->param('workcontent');
            $workcontent_data = [];
            if(isset($workconent)){
                foreach ($workconent as $v){
                    $v['weeks_id'] = $id;
                    $v['create_time'] = time();
                    $workcontent_data[] = $v;
                }
                $ProjectWeeksWorkcontent = new ProjectWeeksWorkcontentModel();
                $re_one = $ProjectWeeksWorkcontent->insertAll($workcontent_data);
            }

            //先删除后新增
            $ProjectWorkplan = new ProjectWeeksWorkplanModel();
            $ProjectWorkplan->where('weeks_id',$id)->delete();
            $workplan = $request->param('workplan');
            $workplan_data = [];
            if(isset($workplan)){
                foreach ($workplan as $vv){
                    $vv['weeks_id'] = $id;
                    $vv['create_time'] = time();
                    $workplan_data[] = $vv;
                }
                $ProjectWorkplan = new ProjectWeeksWorkplanModel();
                $re_two = $ProjectWorkplan->insertAll($workplan_data);
            }

            if(($re!==false) && $re_one && $re_two){
                Db::commit();
                $result = ["status"=>true,"re_id"=>$re,"msg"=>"更新成功！"];
            }else{
                Db::rollback();
                $result = ["status"=>false,"re_id"=>"","msg"=>"更新失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            Db::rollback();
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function weekdel(Request $request)
    {
        try {
            $id = $request->param('id');
            $uid = $request->param('uid');
            if($id){

                Db::startTrans();
                $ProjectWeeksModel = new ProjectWeeksModel;
                $ProjectWeeksWorkcontentModel = new ProjectWeeksWorkcontentModel;
                $ProjectWeeksWorkplanModel = new ProjectWeeksWorkplanModel;
                $re = $ProjectWeeksModel->where('id',$id)->where('uid',$uid)->delete();
                $re_one = $ProjectWeeksWorkcontentModel->where('weeks_id',$id)->delete();
                $re_two = $ProjectWeeksWorkplanModel->where('weeks_id',$id)->delete();
                if($re && $re_one && $re_two){
                    Db::commit();
                    $result = ["status"=>true,"msg"=>"删除成功！"];
                    return json($result);
                }else{
                    Db::rollback();
                    $result = ["status"=>false,"msg"=>"删除失败！"];
                    return json($result);
                }

            }else{
                $result = ["status"=>false,"msg"=>"参数必须"];
                return json($result);
            }
        } catch (\Exception $e) {
            Db::rollback();
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }
}
